﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using ProjectStorageLib;
using ProjectStorageDB;
using System.Web.Security;

public partial class Commercial_LogInPage : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Request["ReturnUrl"] != null && Request["ReturnUrl"].ToString().Contains("Administrator"))
            MasterPageFile = "~/Administrator/Admin.master";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        lMess.InnerText = "";
        tbUsername.Focus();
    }
    protected void bLogin_Click(object sender, EventArgs e)
    {
        //locals
        ProjectStorageLib.User.UserProcessor proc = null;
        User user = null;
        string url;
       
        try
        {
            proc = new ProjectStorageLib.User.UserProcessor();

            if (tbUsername.Text.Trim() != "" && tbPassword.Text.Trim() != "")
            {
                if (!proc.IsUserExist(tbUsername.Text, tbPassword.Text))
                    lMess.InnerText = "Wrong User Name or Password";
                else
                {
                    user = proc.GetUserByUserNameAndPassword(tbUsername.Text, tbPassword.Text);
                    Session["UserID"] = user.id_user;
                    Security.CreateCookie(tbUsername.Text, "User");

                    //logon user 
                    if (proc.IsUserAdmin(user.id_user) == true)
                        url = "~/Administrator/Default.aspx";
                    else if (Request["ReturnUrl"].ToString().Contains("Administrator"))
                        url = "~/Default.aspx";
                    else
                        url = FormsAuthentication.GetRedirectUrl(tbUsername.Text, false);

                    Response.Redirect(url, false);
                }
            }
            else
            {
                lMess.InnerText = "Enter User Name and Password!";
            }

        }
        catch (Exception err)
        {
            lMess.InnerText = err.ToString();
        }
        finally
        {
            if (proc != null)
                proc.Dispose();
        }
    }

   
}